<template>
  <Layout>
    <div class="flex flex-ac flex-col">
      <div class="top-img"></div>
      <el-card class="box-card">
        <div slot="header" class="clearfix" style="text-align:center">
          <div class="tabs">
            <div :class="hidden?'tab':'tab active'" @click="show('xszs')">销售助手</div>
            <div :class="!hidden?'tab':'tab active'" @click="show('jk')">骏客</div>
          </div>
        </div>
        <div>
          <el-form :model="model" ref="model" class="flex flex-jc flex-ac" :rules="rules">
            <div class="inputs flex flex-col flex-ac flex-jc">
              <el-form-item prop="Jxsh" :hidden="hidden">
                <el-input placeholder="请输入经销商号" v-model="model.Jxsh" @keyup.enter.native="login">
                  <i slot="prefix" class="jxsh"></i>
                </el-input>
              </el-form-item>
              <el-form-item prop="LoginName">
                <el-input :placeholder="!hidden?'请输入操作员名称':'请输入用户名'" v-model="model.LoginName"
                  @keyup.enter.native="login">
                  <i slot="prefix" class="xm"></i>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input placeholder="请输入密码" type="password" v-model="model.password" @keyup.enter.native="login">
                  <i slot="prefix" class="mm"></i>
                </el-input>
              </el-form-item>
              <!-- <el-form-item prop="password">
                <el-input class="code-input" placeholder="请输入图形验证码">
                  <i slot="prefix" class="yzm"></i>
                  <div class="flex flex-ac" slot="append">
                    <img src alt class="code" />
                    <i class="sx"></i>
                  </div>
                </el-input>
              </el-form-item>-->
              <el-form-item prop="code">
                <el-input class="code-input" v-model="model.code" @keyup.enter.native="login" placeholder="请输入图形验证码">
                  <i slot="prefix" class="yzm"></i>
                  <div class="flex flex-ac" @click="refreshCode" slot="append">
                    <!-- <img src alt class="code" /> -->
                    <Identify :identifyCode="identifyCode" :contentWidth="110" :contentHeight="34" class="code">
                    </Identify>
                    <i class="sx"></i>
                  </div>
                </el-input>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="flex flex-jc flex-ac flex-col">
          <button style="width:170px;margin-top:17px;margin-bottom:6px" class="ce-button not-hover primary"
            @click="login">登录</button>
          <!-- <div class="mini">忘记密码</div> -->
        </div>
      </el-card>
    </div>
  </Layout>
</template>
<script>
  import "@/assets/styles/index.scss";
  import Layout from "./layout";
  import { deepClone } from "@/utils";
  import { setToken, getToken } from "@/utils/auth";
  import { login, sgmwlogin, sgmwloginjk } from "@/api/user";
  import { validatenull } from "@/utils/validate";
  import Identify from "@/components/Identify";

  const defaulModel = {
    LoginName: "",
    password: "",
    orgCode: "",
    phone: "",
    Jxsh: "",
    code: "",
    UserType: "Teacher"
  };

  export default {
    components: {
      Layout,
      Identify
    },
    data() {
      const validateCode = (rule, value, callback) => {
        if (validatenull(value)) {
          callback(new Error("验证码必须填写"));
        } else if (value.toLowerCase() !== this.identifyCode.toLowerCase()) {
          callback(new Error("验证码不正确,请重新输入"));
        } else {
          callback();
        }
      };
      return {
        model: deepClone(defaulModel),
        loading: false,
        infoModel: {
          userId: "",
          phone: "",
          email: ""
        },
        identifyCodes: "1234567890abcdefjhijklinopqrsduvwxyz",
        identifyCode: "",
        hidden: false,
        rules: {
          Jxsh: [
            { required: true, message: "经销商号必须填写", trigger: "blur" }
          ],
          LoginName: [
            { required: true, message: "操作员名称必须填写", trigger: "blur" }
          ],
          password: [
            { required: true, message: "密码必须填写", trigger: "blur" }
          ],
          code: [{ required: true, trigger: "blur", validator: validateCode }]
        }
      };
    },
    computed: {
      // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存
    },
    created() {
      // 实例创建完成后执行的代码
      if (getToken()) {
        this.$router.push("/home");
      }
      // 初始化验证码
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    methods: {
      login() {
        var v = true;
        this.$refs.model.validate(valid => {
          var v = valid;
          if (valid) {
            if (this.hidden) {
              this.model.UserType = 'jk'
              this.$store
                .dispatch("user/login", this.model)
                .then(res => {
                  if (!validatenull(res.access_token)) {
                    this.$router.push({ path: "/" });
                  }
                  // else {
                  //   Message({
                  //     message: "用户名或密码错误，请重新输入",
                  //     type: "error",
                  //     duration: 5 * 1000
                  //   });
                  // }
                  // this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
                  // this.loading = false
                })
                .catch(() => {
                  //this.loading = false
                });
            } else {
              this.model.UserType = 'jxs'
              this.$store
                .dispatch("user/login", this.model)
                .then(res => {
                  if (!validatenull(res.access_token)) {
                    this.$router.push({ path: "/" });
                  }
                  // else {
                  //   Message({
                  //     message: "用户名或密码错误，请重新输入",
                  //     type: "error",
                  //     duration: 5 * 1000
                  //   });
                  // }
                  // this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
                  // this.loading = false
                })
                .catch(() => {
                  //this.loading = false
                });
            }
          } else {
            console.log("error submit!!");
            return false;
          }
        });

        // if (!v) {
        //   //验证不通过
        //   return false;
        // }
        // var res = await sgmwlogin(this.model);
        // console.log(res);
        // if (res && res.code == 200) {
        //   setToken(res.data.Token);
        //   this.$router.push("/");
        // }
      },
      // 重置验证码
      refreshCode() {
        this.identifyCode = "";
        this.makeCode(this.identifyCodes, 4);
      },
      makeCode(o, l) {
        for (let i = 0; i < l; i++) {
          this.identifyCode += this.identifyCodes[
            this.randomNum(0, this.identifyCodes.length)
          ];
        }
      },
      randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
      },
      show(userType) {
        if (userType === "jk") {
          if (!this.model.Jxsh) this.model.Jxsh = "000000";
          this.hidden = true;
        } else {
          this.hidden = false;
        }
      }

      // methods: {
      //   async login() {
      //     var v = true;
      //     this.$refs.model.validate(valid => {
      //       var v = valid;
      //       if (valid) {
      //         this.$store.dispatch('user/sgmwlogin', this.model)
      //           .then(response => {
      //             // this.$router.push("/");

      //             var s = response;

      //               this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
      //             // this.loading = false
      //           })
      //           .catch(() => {
      //             //this.loading = false
      //           })
      //       } else {
      //         console.log("error submit!!");
      //         return false;
      //       }
      //     });

      //     // if (!v) {
      //     //   //验证不通过
      //     //   return false;
      //     // }
      //     // var res = await sgmwlogin(this.model);
      //     // console.log(res);
      //     // if (res && res.code == 200) {
      //     //   setToken(res.data.Token);
      //     //   this.$router.push("/");
      //     // }
      //   },
      //   // 重置验证码
      //   refreshCode() {
      //     this.identifyCode = "";
      //     this.makeCode(this.identifyCodes, 4);
      //   },
      //   makeCode(o, l) {
      //     for (let i = 0; i < l; i++) {
      //       this.identifyCode += this.identifyCodes[
      //         this.randomNum(0, this.identifyCodes.length)
      //       ];
      //     }
      //   },
      //   randomNum(min, max) {
      //     return Math.floor(Math.random() * (max - min) + min);
      //   }
      // },
    }
  };
</script>


<style lang="scss" scoped>
  /deep/ {
    .mini {
      cursor: pointer;
      font-size: 14px;
      margin-top: 6px;
      color: rgba(153, 153, 153, 1);
    }

    .top-img {
      @include wh(280, 238);
      @include bg("~@/assets/images/login/0_3jxs@2x.png");
    }

    .el-card {
      border-radius: 20px;
      box-shadow: 0px 8px 16px 0px rgba(72, 72, 72, 0.15);
      width: 544px;
      height: 380px;
      margin-bottom: 100px;
    }

    .jxsh {
      @include wh(50, 72);
      @include bgwh("~@/assets/images/login/3_3azzm@2x.png", 30, 32);
    }

    .xm {
      @include wh(50, 72);
      @include bgwh("~@/assets/images/login/3_2ayhm@2x.png", 32, 30);
    }

    .mm {
      @include wh(50, 72);
      @include bgwh("~@/assets/images/login/3_2amm@2x.png", 30, 30);
    }

    .yzm {
      @include wh(50, 72);
      @include bgwh("~@/assets/images/login/0_2yzm@2x.png", 34, 30);
    }

    .sx {
      @include wh(50, 72);
      @include bgwh("~@/assets/images/login/0_2sx@2x.png", 30, 30);
    }

    .code-input {
      position: relative;

      input {
        padding-right: 154px;
      }

      .el-input-group__append {
        position: absolute;
        right: 4px;
        top: 1px;
        bottom: 1px;
        width: 148px;
        border: 0;
        background-color: #fff;
        padding: 0;
      }

      .sx {
        width: 37px !important;
      }
    }

    input {
      border-radius: 0px !important;
    }

    .code {
      display: block;
      width: 111px;
      height: 34px;
      margin-top: -2px;
      background: #ebebeb;
    }

    .el-input {
      height: 36px;
    }

    .el-card__header {
      padding: 0;
      height: 54px !important;
      line-height: 54px;
    }

    .el-input__prefix {
      height: 36px;
    }

    .el-form-item__content {
      line-height: 36px;
    }
  }

  .tabs {
    display: flex;
    align-items: center;
    justify-content: center;

    .tab {
      position: relative;

      &+.tab {
        margin-left: 50px;
      }

      cursor: pointer;
      min-width: 64px;
      font-size: 16px;
      font-weight: 500;
      color: rgba(153, 153, 153, 1);

      &.active,
      &:hover {
        font-size: 16px;
        font-weight: 600;
        color: rgba(35, 46, 58, 1);

        &::after {
          content: "";
          height: 4px;
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(255, 201, 45, 1);
        }
      }
    }
  }

  .inputs {
    padding: 5px;

    /deep/ {
      .el-form-item {
        margin-bottom: 0 !important;

        &+.el-form-item {
          margin-top: 16px;
        }
      }

      .el-input__inner {
        width: 357px;
        height: 36px;
        line-height: 36px;
        border-radius: 8px;
        border: 1px solid rgba(0, 0, 0, 0.1);
      }
    }
  }

  /deep/ {
    .el-card__header {
      height: 57px;
      box-sizing: border-box;
      font-size: 16px;
      color: #232e3a;
    }
  }
</style>